package com.sunyw.xyz.utils;

import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Range;
import org.springframework.core.io.ClassPathResource;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.poi.hwpf.HWPFDocument;

public class DocUtils {

    private static final String upFileUrl = "D:/down/";

    /**
     * 替换.doc模板生成文件
     *
     * @param filePath 模板文件路径
     * @param replace  key为模板中被替换数据,value为替换数据
     * @return fileName 生成的doc文件名称
     * @author sunyw
     */
    public String createDoc(String filePath, Map<String, String> replace) {
        String fileName = null;
        InputStream fileInputStream = null;
        OutputStream outStream = null;
        try {
            fileInputStream = new ClassPathResource(filePath).getInputStream();
            HWPFDocument doc = new HWPFDocument(fileInputStream);
            Range range = doc.getRange();

            Set<String> strings = replace.keySet();
            for (String string : strings) {
                //循环替换模板数据,key为被替换数据,value为替换后数据
                range.replaceText(string, replace.get(string));
            }
            WordToHtmlConverter wordToHtmlConverter =
                    new WordToHtmlConverter(
                            DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
            //解析doc
            wordToHtmlConverter.processDocument(doc);
            //文档生成
            Document htmlDocument = wordToHtmlConverter.getDocument();
            //生成文件名称
            fileName = UUID.randomUUID() + ".doc";
            File htmlFile = new File(upFileUrl + fileName);
            outStream = new FileOutputStream(htmlFile);
            DOMSource domSource = new DOMSource(htmlDocument);
            StreamResult streamResult = new StreamResult(outStream);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer serializer = factory.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");
            serializer.transform(domSource, streamResult);
        } catch (Exception e) {
            System.out.println("生成doc文件失败");
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                e.getMessage();
            }

        }
        return fileName;
    }
}
